package com.soft.work.action;

import javax.annotation.Resource;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.soft.core.action.ActivitiBaseAction;
import com.soft.core.dao.GenericDao;
import com.soft.core.utils.StatusEnum;
import com.soft.work.dao.ExpenseDao;
import com.soft.work.domain.Expense;

@Controller
@Scope("prototype")
public class ExpenseAction extends ActivitiBaseAction<Expense> {

	private ExpenseDao expenseDao;
	
	
	@Resource
	public void setExpenseDao(ExpenseDao expenseDao) {
		this.expenseDao = expenseDao;
	}

	@Override
	public GenericDao<Expense> getDao() {
		return expenseDao;
	}
	
	@Override
	public void beforeSave(Expense model) {
		if (null == model.getUser()) {
			model.setUser(getCurrentUser());
		}
		if (null == model.getStatus()) {
			model.setStatus(StatusEnum.unstart.getValue());
		}
	}
	
	@Override
	public void beforFind(DetachedCriteria criteria) {
		if (null != model.getStartMoney()) {
			criteria.add(Restrictions.ge("money", model.getStartMoney()));
		}
		if (null != model.getEndMoney()) {
			criteria.add(Restrictions.le("money", model.getEndMoney()));
		}
		
		if (null != model.getStatus()) {
			if (StatusEnum.finished.getValue().equals(model.getStatus())) {
				Criterion c1 = Restrictions.eq("status", StatusEnum.success.getValue());
				Criterion c2 = Restrictions.eq("status", StatusEnum.fail.getValue());
				criteria.add(Restrictions.or(c1, c2));
			} else {
				criteria.add(Restrictions.eq("status", model.getStatus()));
			}
		}
		if (null == model.getQueryByAllUser() || "".equals(model.getQueryByAllUser())) {
			criteria.createAlias("user", "u");
			criteria.add(Restrictions.eq("u.id", getCurrentUser().getId()));
		}
	}

}
